import asyncio

from semantic_kernel.connectors.ai.open_ai import OpenAIChatCompletion
from semantic_kernel.contents import ChatHistory
from semantic_kernel.prompt_template.prompt_template_config import PromptTemplateConfig
from semantic_kernel.prompt_template.input_variable import InputVariable
from semantic_kernel.functions import KernelArguments
import semantic_kernel as sk
import os



async def run_function(*args):
   return await kernel.invoke(*args)

if __name__=='__main__':
   os.environ["OPENAI_API_KEY"] = os.environ["OPENAI_API_KEY_ZHIHU"]
   os.environ["OPENAI_BASE_URL"] = os.environ["OPENAI_API_BASE_ZHIHU"]

   template = """"
   对话历史如下:
   {{$history}}

   User:{{$input}}
   Assistant:
   """

   kernel = sk.Kernel()


   service_id = "MyChatService"
   plugin_name = "MyChatPlguin"
   service = OpenAIChatCompletion(service_id=service_id,api_key=os.environ.get("OPENAI_API_KEY_ZHIHU"),ai_model_id="gpt-4o")
   kernel.add_service(service=service)

   #获取当前默认设定
   req_settings = kernel.get_service(service_id).get_prompt_execution_settings_class()(service_id=service_id)
   #定义 Prompt 模板
   #模板中,变量以{{$变量名}}表示
   prompt_template_config = PromptTemplateConfig(template=template,description="A general prompt template",
      execution_settings={service_id:req_settings},input_variables=[InputVariable(name="history",description="Conversation history",is_required=True),
                                                                    InputVariable(name="input",description="User input",is_required=True)])
   #注册 function
   topical_joke_function = kernel.add_function(function_name="ChatFunction",plugin_name=plugin_name,prompt_template_config=prompt_template_config)

   chatHistory=ChatHistory()
   chatHistory.add_system_message("You are a helpful chatbot who is good at answering user's questions.")
   #调用函数
   while(True):
       user_input = input("User:")
       print("User:" + user_input)

       if user_input.lower()=="exit":
           break

       #调用函数
       result = asyncio.run(run_function(topical_joke_function,KernelArguments(history=chatHistory,input=user_input)))

       print("Assistant:",result.value[0].content)

       #将用户输入和函数返回结果添加到历史记录中
       chatHistory.add_user_message(user_input)
       chatHistory.add_assistant_message(str(result.value[0].content))

   print("结束")